﻿using Business.Parsers;
using HtmlAgilityPack;
using OpenPop.Mime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Business {
    public class ResumeParser {
        public Resume Parse(Message message) {
            Resume resume;

            var mailMessage = message.ToMailMessage();
            if (mailMessage.Subject.Contains("51job.com"))
                resume = new Job51ResumeParser().Parse(mailMessage.Body);
            else if (mailMessage.Subject.Contains("Zhaopin.com"))
                resume = new ZhaoPinResumeParser().Parse(mailMessage.Body);
            else
                throw new ApplicationException("未知网站的简历");

            resume.MessageId = message.Headers.MessageId;
            resume.HtmlBody = GetCleanHtmlBody(resume.HtmlBody);
            resume.TextBody = GetTextBody(resume.HtmlBody);

            return resume;
        }

        /// <summary>
        /// 去掉邮件正文中的样式信息，包括元素的样式属性和style标签
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        private string GetCleanHtmlBody(string body) {
            return Regex.Replace(body, "\\s+style=\".*?\"|<style(\\s+.*?)?>.*?</style>|width=\"\\d+(px)?\"", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }

        private string GetTextBody(string body) {
            var doc = new HtmlDocument();
            doc.LoadHtml(body);
            var text = doc.DocumentNode.InnerText;
            return Regex.Replace(HttpUtility.HtmlDecode(text), @"\s+", string.Empty, RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }
    }
}
